package com.lz.ovuola.util.aop;

import java.io.Serializable;

import javax.annotation.Resource;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;

import com.lz.ovuola.util.annotation.Cache;
import com.lz.ovuola.util.constant.RedisCacheConsts;
import com.lz.ovuola.util.redis.RedisTemplateRepository;
import com.lz.ovuola.util.threadlocal.UserContextHolder;

@Order(-9)
@Aspect
// 注解的方式配置aop
@Configuration
public class RedisCacheAspect {
	private Logger logger = LoggerFactory.getLogger(RedisCacheAspect.class);

	@Resource
	private RedisTemplateRepository redisTemplateRepository;

	@Around(PointCut.TARGET_CACHE)
	public Object around(ProceedingJoinPoint pjp, Cache cache) throws Throwable {
		Serializable retVal = null;
		if (cache != null && cache.cacheable()) {
			String className = pjp.getTarget().getClass().getTypeName();
			MethodSignature signature = (MethodSignature) pjp.getSignature();
			String methodName = signature.getMethod().getName();
			Integer userId = UserContextHolder.get().getUserId();
			String key = new StringBuilder().append(userId).append("_")
					.append(className).append("_").append(methodName)
					.toString();
			retVal = redisTemplateRepository.get(RedisCacheConsts.OVUOLA_CACHE,
					key);
			// 缓存不存在或无效，将结果缓存
			if (retVal == null) {
				retVal = (Serializable) pjp.proceed();
				redisTemplateRepository.setEx(RedisCacheConsts.OVUOLA_CACHE,
						key, retVal, cache.expiration(), cache.unit());
				logger.info("---用户id:{} 正在操作类:{}的方法:{} 缓存不存在，将结果集缓存 ", userId,
						className, methodName);
			}
		} else {
			retVal = (Serializable) pjp.proceed();
		}
		return retVal;
	}
}